package cloud.gosun.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;

/**
 * Created by sanairika on 2016/07/24.
 */
public class Demo1Servlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            String num = req.getParameter("num");
            Integer seed = Integer.valueOf(num);
            StringBuilder sb = new StringBuilder();
            sb.append("参数num: ").append(num).append("\r\n").append("\r\n");
            List<Integer> list = new ArrayList<>();
            for (int i = 0; i < 10; i++) {
                int ran = ThreadLocalRandom.current().nextInt(100);
                list.add(ran);
                sb.append("生成的随机数: ").append(ran).append(", 与num的乘积: ").append(ran * seed).append("\r\n");
            }
            int sum = list.stream().reduce((a, b) -> a + b).get();
            sb.append("\r\n").append("平均数: ").append(((double) (sum * seed)) / 10d);
            resp.getWriter().print(sb.toString());
        } catch (NumberFormatException | NullPointerException ex) {
            resp.getWriter().print("请输入正确的参数:num");
            resp.setStatus(400);
        }
    }
}
